<template>
  <div ref="mapContainer" id="mapContainer" class="map"></div>
</template>
<script setup>
import { onMounted, ref, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { mapSetting } from "#/api/map";
import {
  ElMessage,
} from "element-plus";

const map = ref(null);
const mapContainer = ref(null)
const props = defineProps({
  airportList: {
    type: Array,
    default: () => [],
  },
  onlineList: {
    type: Array,
    default: () => [],
  },
  airportData: {
    type: Object,
    default: () => { },
  },
});

const lineList = ref([
  {
    name: "空闲",
    status: '0',
  },
  {
    name: "航线任务中",
    status: '1',
  },
  {
    name: "手动飞行中",
    status: '2',
  },
]);
const getLineList = (status) => {
  return lineList.value.find((item) => item.status == status)?.name;
};

// 机场状态配置 - 4种图片和4种文字颜色
const airportStatusConfig = {
  空闲中: { image: "/static/airport6.png", color: "#52c41a" },
  起飞准备中: { image: "/static/airport1.png", color: "#2f69eb" }, //蓝色
  航线任务中: { image: "/static/airport7.png", color: "#ff4d4f" },
  手动任务中: { image: "/static/airport7.png", color: "#ff4d4f" },
  离线: { image: "/static/airport2.png", color: "#ff9000" },
};
// 飞行状态配置
const flightStatusConfig = {
  离线: { image: "/static/airport3.png", color: "#00adb8" },
  航线任务中: { image: "/static/airport3.png", color: "#00adb8" },
  手动任务中: { image: "/static/airport3.png", color: "#00adb8" },
};

// 获取机场状态配置，如果没有匹配的状态则使用默认配置
const getAirportConfig = (status) => {
  return airportStatusConfig[status] || airportStatusConfig["离线"];
};

const getFlightStatusConfig = (status) => {
  return flightStatusConfig[status] || flightStatusConfig["离线"];
};

// 清除所有机场标记
const clearAirportMarkers = () => {
  if (!map.value) return;
  // 清除所有覆盖物
  map.value.clearMap();
};
let centerlnglat = [119.904792, 30.247956];
// 动态加载高德地图 JS API
const loadAMap = async () => {
  if (props.airportList && props.airportList.length > 0) {
    centerlnglat = [
      props.airportList[0].longitude,
      props.airportList[0].latitude,
    ];
  }
  try {
    await AMapLoader.load({
      key: mapSetting.mapKey,
      securityJsCode: mapSetting.mapSecurity,
      version: "2.0",
    });
    setMap()
  } catch (error) {
    ElMessage.error("地图初始化失败: " + error.message);
  }
};
const setMap = () => {
  if (!map.value) {
    map.value = new AMap.Map(mapContainer.value, {
      zoom: 16,
      center: centerlnglat,
      // pitch: 60, // 俯仰角度
      // viewMode: '3D', // 启用 3D 模式
      mapStyle: "amap://styles/darkblue",
    });
  }
  // console.log(map.value, props.airportList)
  if (props.airportList && props.airportList.length > 0) {
    createAirportMarker();
  }
}
// 可以把 map 挂载到组件实例或全局状态中，用于后续操作
// window.map = map; // 示例用途，调试时可查看

// 如果已经有机场数据，则创建标记

// 创建机场标记
const createAirportMarker = () => {
  if (!map.value || props.airportList.length === 0) return;
  try {
    // 先清除之前的标记
    clearAirportMarkers();
    let markers = []
    props.airportList.forEach((airport) => {
      const config = getAirportConfig(airport.status);
      const marker = new AMap.Marker({
        position: [airport.longitude, airport.latitude],
        content: `<div class="airport-marker">
            <img src="${config.image
          }" width="50" height="50" style="display: block;" />
            <p class="text" style="color: ${config.color}">${airport.airportName
          }</p>
            <p class="text" style="color: ${config.color}">(${(airport.flightStatus || airport.flightStatus === 0) ? getLineList(airport.flightStatus) : "离线"
          })</p>
        </div>`,
        offset: new AMap.Pixel(-20, -30),
        zIndex: 1000,
      });
      markers.push(marker)
      // map.value.add(marker);
    });
    props.onlineList.forEach((airport) => {
      const config = getAirportConfig(airport.status);
      const marker = new AMap.Marker({
        position: [airport.longitude, airport.latitude],
        content: `<div class="airport-marker">
            <img src="/static/airport3.png" width="50" height="50" style="display: block;" />
            <p class="text" style="color: #00adb8">${airport.droneName}</p>
            <p class="text" style="color: #00adb8">(${airport.flightStatus ? getLineList(airport.flightStatus) : "离线"
          })</p>
        </div>`,
        offset: new AMap.Pixel(-25, -25),
        zIndex: 0,
      });
      // map.value.add(marker);
      markers.push(marker)
    });

    // 设置地图中心点到第一个机场
    // const center = [
    //   props.airportList[0].longitude,
    //   props.airportList[0].latitude,
    // ];
    // map.value.setCenter(center);
    map.value.add(markers)
    setTimeout(() => {
      map.value.setFitView()
    }, 1000);
  } catch (error) {
    console.error("创建机场图标时出错:", error);
  }
};

// 监听 airportList 变化，重新渲染标记
// watch(
//   () => props.airportList,
//   (newList) => {
//     if (map.value && newList && newList.length > 0) {
//       createAirportMarker();
//     }
//   },
//   { deep: true, immediate: false }
// );
// watch(
//   () => props.airportData,
//   (newData) => {
//     if (map.value && newData) {
//       // 设置地图中心点到第一个机场
//       const center = [newData.longitude, newData.latitude];
//       map.value.setCenter(center);
//     }
//   }
// );

// 组件挂载后加载地图
onMounted(async () => {
  try {
    await loadAMap();
    // await initMap(); // 再初始化地图
  } catch (error) {
    console.error("加载高德地图失败:", error);
  }
});
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.map {
  width: 100%;
  height: 100%;
}

.location-info {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 10px;
  background: rgb(255 255 255 / 90%);
  border-radius: 4px;
  box-shadow: 0 2px 6px rgb(0 0 0 / 10%);
}

:deep(.airport-marker) {
  color: #ffffff;
  font-size: 14px;
  font-weight: bold;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
  pointer-events: none;
  white-space: nowrap;
  text-align: center;
  // position: absolute;
  // left: 0;
  // top: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

:deep(.text) {
  margin: 2px 0 0 0;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  font-weight: normal;
  text-overflow: ellipsis;
}

:deep(.amap-copyright) {
  display: none !important;
}
</style>
